import webapp2
import jinja2
import os
from cloudcash import model
from google.appengine.api import users

JINJA = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class IndexPage(webapp2.RequestHandler):
	def get(self):
		if users.get_current_user():
			template = JINJA.get_template('web/index.html')
			self.response.out.write(template.render())
		else:
			return webapp2.redirect(users.create_login_url('/'))

class BookList(webapp2.RequestHandler):
	def get(self):
		template = JINJA.get_template('web/bookList.html')
		booksByUser = {}
		for book in model.Book.listAll():
			userKey = book.key.parent()
			if userKey not in booksByUser:
				booksByUser[userKey] = [book]
			else:
				booksByUser[userKey].append(book)
		self.response.out.write(template.render(books=model.Book.listByCurrentUser(), booksByUser=booksByUser))

class BookCreate(webapp2.RequestHandler):
	def post(self):
		name = self.request.get('name').strip()
		model.Book(name = name).put()
		return webapp2.redirect('/bookList')

class AccountList(webapp2.RequestHandler):
	def get(self):
		template = JINJA.get_template('web/accountList.html')
		book = model.Book.getByUrlSafeKey(self.request.get('book'))
		self.response.out.write(template.render(book=book, accounts=model.Account.listByBook(book), categories=model.AccountCategories))

class AccountCreate(webapp2.RequestHandler):
	def post(self):
		name = self.request.get('name').strip()
		description = self.request.get('description').strip()
		categoryKey = int(self.request.get('categoryKey'))
		category = model.AccountCategories[categoryKey]
		book = model.Book.getByUrlSafeKey(self.request.get('book'))
		model.Account(parent=book.key, name=name, description=description, category=categoryKey).put()
		return webapp2.redirect('/accountList?book=' + book.key.urlsafe())

class AccountShow(webapp2.RequestHandler):
	def get(self):
		account = model.Account.getByUrlSafeKey(self.request.get('account'))
		template = JINJA.get_template('web/accountShow.html')
		self.response.out.write(template.render(account=account))

app = webapp2.WSGIApplication([
	('/', IndexPage),
	('/bookList', BookList),
	('/bookCreate', BookCreate),
	('/accountList', AccountList),
	('/accountCreate', AccountCreate),
	('/accountShow', AccountShow),
	],
	debug=False)
